package com.cl.short_video_java.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.Data;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cl.short_video_java.common.Result;
import com.cl.short_video_java.config.AliPayConfig;
import com.cl.short_video_java.exception.WebException;
import com.cl.short_video_java.pojo.VideoShop;
import com.cl.short_video_java.pojo.VideoShopOrder;
import com.cl.short_video_java.service.PayService;
import com.cl.short_video_java.service.SysSettingService;
import com.cl.short_video_java.service.VideoShopOrderService;
import com.cl.short_video_java.service.VideoShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.logging.SimpleFormatter;

/**
 * @Author 付
 * @Date 2024-11-16 10:25
 * @Version 1.0
 * @description
 * @since 1.0
 */

@Service
@Slf4j
public class PayServiceImpl implements PayService {


	private VideoShopOrderService orderService;
	private VideoShopService shopService;
	private AlipayClient alipayClient;
	private AlipayClient alipayClientGold;
	private SysSettingService sysSettingService;

	@Autowired
	PayServiceImpl(VideoShopOrderService orderService,
				   VideoShopService shopService,
				   AlipayClient alipayClient,
				   SysSettingService sysSettingService,
				   AlipayClient alipayClientGold) {
		this.orderService = orderService;
		this.shopService = shopService;
		this.alipayClient = alipayClient;
		this.sysSettingService = sysSettingService;
		this.alipayClientGold = alipayClientGold;
	}


	/**
	 * 支付宝支付创建支付请求
	 *
	 * @param shopId  商品id
	 * @param request
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String tradeCreate(Integer shopId, HttpServletRequest request) {
		try {
			VideoShopOrder order = orderService.createOrder(shopId, request);
			VideoShop videoShop = shopService.getById(order.getShopId());
			AlipayClient alipayClient1 = chooseClient(videoShop.getType());
			log.info("生成的订单信息：" + order);

			// 调用支付宝请求
//			AlipayTradeWapPayRequest tradePayRequest = new AlipayTradeWapPayRequest();
			AlipayTradePrecreateRequest tradePayRequest = new AlipayTradePrecreateRequest();
			tradePayRequest.setReturnUrl(sysSettingService.getSysSettingByKey("alipay_return_url"));
			tradePayRequest.setNotifyUrl(sysSettingService.getSysSettingByKey("alipay_notify_url"));

			// 请求参数
			AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
			model.setOutTradeNo(order.getOrderId());

			model.setTotalAmount(String.valueOf(order.getPayPrice()));
			model.setSubject(order.getTitle());
			model.setTimeoutExpress("10m");
//			Date date = new Date();
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			String timeString = sdf.format(date);
//			model.setTimeExpire(String.valueOf(timeString));

			tradePayRequest.setBizModel(model);
			AlipayTradePrecreateResponse response = alipayClient1.execute(tradePayRequest);
			if (response.isSuccess()) {
				log.info("调用成功=============================>" + response.getBody());
			} else {
				log.error("调用失败=============================>" + response);
				orderService.remove(new QueryWrapper<VideoShopOrder>().eq("order_id", shopId));
				throw new WebException("订单创建失败");
			}
			JSONObject jsonObject = JSONObject.parseObject(response.getBody());
			String qrUrl = jsonObject.getJSONObject("alipay_trade_precreate_response").get("qr_code").toString();
			BufferedImage generate = QrCodeUtil.generate(qrUrl, 300, 300);
			//输出流
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			try {
				ImageIO.write(generate, "png", stream);
			} catch (IOException e) {
				e.printStackTrace();
			}
			String base64 = Base64.encode(stream.toByteArray());
			return base64;
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new WebException("创建订单失败");
		}
	}

	private AlipayClient chooseClient(Integer type) {
		return type == 1 ? alipayClient : alipayClientGold;
	}
}
